﻿#light

open System.IO
open System.IO.IsolatedStorage

open Microsoft.FSharp.Control

/// The internal type of messages for the agent
type Message = Set of string * obj | Fetch of string * AsyncReplyChannel<obj> | Stop

let frameworkDir = typeof<obj>.Assembly.Location

let defaultAssemblies =
  [ "mscorlib.dll";
    "System.dll"
    "System.Data.dll";
    "System.Drawing.dll";
    "System.Web.dll";
    "System.Windows.Forms.dll" ]

let defaultSettings = []

let getInitSettings() =
    let store = IsolatedStorageFile.GetUserStoreForApplication()
    if store.GetFileNames("settings").Length = 0 then
        defaultSettings
    else
        let settings = new IsolatedStorageFileStream("settings", FileMode.Open, store)
        []
 
type StateDictionary() =
    let counter = MailboxProcessor.Start(fun inbox ->
             // The states of the message processing state machine...
             let rec loop(state : Map<string,obj>) =
                async { let! msg = inbox.Receive()
                        match msg with
                        | Set (key, value) ->
                            if state.ContainsKey key then
                                state.Remove key |> ignore
                            return! loop(state.Add (key, value) )
                               
                        | Stop ->
                            // exit
                            return ()
                        | Fetch (key, replyChannel)  ->
                            // post response to reply channel and continue
                            do replyChannel.Reply(state.[key])
                            return! loop(state) }
 
             // The initial state of the message processing state machine...
             loop(Map.empty))
 
    member a.AddWord(key,value) = counter.Post(Set(key,value))
    member a.Stop() = counter.Post(Stop)
    member a.Fetch(key) = counter.PostAndReply(fun replyChannel -> Fetch(key,replyChannel))
